<template>
  <div class="wrap">
    <!-- 头部 -->
    <div class="head">
      <img v-if="dataReady" :src="appInfo.headImgUrl">
      <img v-else src="/static/default-head.png">
      <div class="game-info">
        <div class="info-top">
          <div class="name">{{appInfo.nickname}}</div>
          <div class="gold">
            <img src="/static/gold.png"> {{appInfo.money}}
          </div>
        </div>
        <div class="info-bottom">
          等级{{appInfo.grade}}
          <div class="exp-process">
            <div class="exp-inner" :style="expStyle"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 内容个 -->
    <div class="content">
      <!-- 排位入口 -->
      <div class="rank" @click="rankStart">
        <img src="/static/entry/rank.png">
        <!-- 段位信息 -->
        <div class="rank-name">{{appInfo.paragraphName}}</div>
      </div>
      <!-- 每周闯关和匹配赛 -->
      <!-- <div class="g-box">
        <img class="week-entry" src="/static/entry/week-active.png" @click="weekChallenge">
        <img class="normal-entry" src="/static/entry/day-challenge.png" @click="normalGame">
      </div> -->
      <!-- 每日挑战 -->
      <div class="day" @click="dayChallenge">
        <img src="/static/entry/day-challenge.png">
        <!-- <div class="d-number">{{dayCount}}关</div> -->
      </div>
      <div class="f-battle">
        <img src="/static/entry/friend-battle.png"@click="battleClickHandle">
        <!-- <div class="f-btn" @click="battleClickHandle">好友对战</div> -->
      </div>
        <div class="small-btn">
          <img src="/static/entry/rank-entry.png" @click="toRankList">
          <button plain="true" open-type="contact" class="service"><img src="/static/entry/service-entry.png" alt=""></button>
      </div>
    </div>
  
    <!-- 登录页面 -->
    <div class="login-page" v-if="isAuthorize=='0'">
      <img src="/static/logo.png" alt="">
      <button class="login-btn" @getuserinfo="getUserInfo($event)" open-type="getUserInfo" lang="zh_CN">登录</button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  onShareAppMessage: function(res) {
    return {
      title: "万象大考",
      // imageUrl: shareConfig.url,
      path: "/pages/entry/index",
      success: res => {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    };
  },
  data() {
    return {
      dataReady: false,
      gradeList: [],
      expStyle: ""
    };
  },
  watch: {
    dataReady(value) {
      console.log("watch")
      if (value) {
        this.initPage();
      }
    }
  },
  computed: {
    ...mapState({
      isAuthorize: state => state.isAuthorize,
      userInfo: state => state.userInfo,
      IMGHEAD: state => state.IMGHEAD,
      appInfo: state => state.appInfo,
      dayCount: state => state.dayCount,
      roomId: state => state.fStore.roomId,
      roomStatus: state => state.fStore.roomStatus
    })
  },
  onShow() {
    console.log("onShow")
    if (this.dataReady) {
      this.initPage();
    }
  },
  onHide(){
    console.log("onHide")
  },
  mounted() {
    console.log("git版本-->", "v2.0");
    this.login();
  },
  methods: {
    ...mapMutations({
      setAuthorize: "setAuthorize",
      setUserInfo: "setUserInfo",
      setAppInfo: "setAppInfo",
      setSessionId: "setSessionId",
      setDayCount: "setDayCount",
      setOpenId: "setOpenId",
      setRoomId: "fStore/setRoomId",
      setRoomStatus: "fStore/setRoomStatus"
    }),
    login() {
      // 微信登录
      wx.login({
        success: res => {
          let code = res.code;
          // 登录
          wx.showLoading({
            title: "登录中,请稍后",
            mask: true
          });
          this.fly.get("/login", { code: code }).then(res => {
            if (res.data.Tag == 1) {
              this.setSessionId(res.data.SessionId); // 全局管理SesionId
              this.setOpenId(res.data.Result.openId); // 全局管理SesionId
              wx.hideLoading();
              // 用户信息初始化
              this.getInit();
              this.hasRoomIdStorage().then(res => {
                if (!res.value) {
                  this.getRoomId();
                }
              });
              this.dataReady = true;
            console.log("login",this.dataReady)
            }
          });
        },
        fail: res => {}
      });
    },
    initPage() {
      this.expStyle = `width:${this.appInfo.expValue /
        this.appInfo.maxExpValue *
        100}%;`;
      this.initStar();
      // 分享卡片进来，判断一下房间状态
     if((this.$root.$mp.appOptions.scene==1007||this.$root.$mp.appOptions.scene==1008)&&this.$root.$mp.query.roomId){
       this.getRoomStatus(this.roomId); //查询房间状态
     }
    },
    initStar() {
      this.gradeList = new Array(3).fill(false);
      if (this.appInfo.paragraph == 1) {
        this.gradeList = [false];
      } else if (this.appInfo.paragraph == 2) {
        this.gradeList = new Array(2).fill(false);
      } else {
        this.gradeList = new Array(3).fill(false);
      }
      for (let i = 0; i < this.appInfo.star; i++) {
        this.gradeList[i] = true;
      }
    },
    toRankList(){
      this.$router.push('/pages/rankPage/index');
    },
    weekChallenge() {
      this.$router.push("/pages/weekChallenge/index");
    },
    rankStart() {
      this.$router.push("/pages/game/index?rankGame=true");
    },
    hasRoomIdStorage() { //是否有本地缓存的 roomId
      return new Promise((resolve, reject) => {
        let returnValue = { value: false };
        wx.getStorage({
          key: "roomId",
          success: res => {
            if (res.data != undefined && res.data != "") {
              returnValue.value = true;
              resolve(returnValue);
            } else {
              returnValue.value = false;
              resolve(returnValue);
            }
          },
          fail: res => {
            returnValue.value = false;
            resolve(returnValue);
          }
        });
      });
    },
    wait() {
      wx.showToast({
        title: "暂未开放,敬请期待",
        icon: "none"
      });
    },
    getInit() {
      this.fly.post("/init").then(res => {
        this.setAppInfo(res.data.Result);
        this.setDayCount(res.data.Result.dayCardNumber);
        this.expStyle = `width:${this.appInfo.expValue /
          this.appInfo.maxExpValue *
          100}%;`;
        this.initStar();
      });
    },
    getUserInfo(event) {
      let data = event.mp.detail.userInfo;
      console.log(data)
      if (data) {
        wx.setStorage({
          //记录授权状态
          key: "isAuthorize",
          data: "1"
        });
        this.setAuthorize(1);
        this.setUserInfo(data);
        this.fly.post("/authorize", {
          //后端授权
          nickName: data.nickName,
          avatarUrl: data.avatarUrl,
          gender: data.gender,
          city: data.city,
          province: data.province,
          country: data.country
        });
      }
    },
    normalGame() {
      this.$router.push("/pages/game/index");
    },
    dayChallenge() {
      this.$router.push("/pages/dayChallenge/rankPage");
    },
    // -------------------------好友对战相关
    battleClickHandle() {
      // TODO
      // 1.进入对战准备房间
      this.apiClickRoom().then(
        res=>{
          if(res==0){
            this.$router.push("/pages/battleRoom/index");
          }
        }
      )
    },
    getRoomId() {
      return new Promise((resolve, reject) => {
        this.fly.post("/room/getRoomId").then(res => {
          this.setRoomId({roomId:res.data.Result.code}); //顺便设置缓存
          resolve(res.data.Result.code);
        });
      });
    },
    apiClickRoom(){
      return new Promise((resolve,reject)=>{
        this.fly.post('/room/clickRoom',{code:this.roomId}).then(res=>{resolve(res.data.Result.isExpire)});
      })
    },
    getRoomStatus(code) {
      // 设置
      let queryRoomId = this.$root.$mp.query.roomId; //获取连接上的挂参
      this.fly
        .post("/room/clickRoom", {
          code: queryRoomId
        })
        .then(res => {
          console.log("res.data.Result.isExpire",res.data.Result.isExpire)
          this.setRoomStatus(res.data.Result.isExpire); // 他人房间状态和自己的房间状态互斥，所以公用
          console.log("isAuthorize",this.isAuthorize)

          if (this.roomStatus == 0 && queryRoomId != undefined&&queryRoomId!=this.roomId&&this.isAuthorize=='1') { //房间状态ok,id存在，id不等于自己，已授权
            console.log('1')
            this.setRoomId({roomId:queryRoomId,from:"invate"}); //更新roomId 为受邀房间
            console.log('2')
            this.$router.push("/pages/battleRoom/index");
            console.log('3')
            
            delete this.$root.$mp.query.roomId;
            console.log('4')
          }
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  height: 100%;
  width: 100%;
  background: #d4eddb;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.head {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  width: 100%;
  height: 164rpx;
  background: #4ab189;
  box-shadow: 0 0 50rpx 15rpx rgba(#4ab189,.5);
  & > img {
    width: 134rpx;
    height: 134rpx;
    border-radius: 4rpx solid #d1e7de;
    border-radius: 50%;
    margin-right: 30rpx;
    box-sizing: border-box;
  }
  .game-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    width: 436rpx;
    color: #fff;
    font-size: 30rpx;
    .info-top,
    .info-bottom {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .info-top {
      margin-bottom: 20rpx;
      justify-content: space-between;
      .name {
        font-size: 36rpx;
        font-weight: bold;
      }
      .gold {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        line-height: 36rpx;
        img {
          width: 36rpx;
          height: 36rpx;
          margin-right: 15rpx;
        }
      }
    }
    .info-bottom {
      justify-content: space-between;
      .exp-process {
        margin-left: 12rpx;
        width: 318rpx;
        height: 14rpx;
        background: #348969;
        box-sizing: border-box;
        border-radius: 1000rpx;
      }
      .exp-inner {
        width: 0%;
        height: 100%;
        background: #fad357;
        border-radius: 1000rpx;
        transition: all 0.2s ease;
      }
    }
  }
}

.content {
  text-align: center;
  padding: 24rpx 20rpx 0 20rpx;
  box-sizing: border-box;
}

.rank {
  position: relative;
  margin-bottom: -10rpx;
  & > img {
    width: 694rpx;
    height: 320rpx;
    vertical-align: top;
  }
  .rank-name {
    position: absolute;
    left: 75rpx;
    bottom: 60rpx;
    color: #fff;
    font-weight: bold;
    font-size: 36rpx;
    width: 250rpx;
    height: 58rpx;
    text-align: left;
    line-height: 58rpx;
  }

}
.g-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: -20rpx;
  .week-entry,
  .normal-entry {
    width: 348rpx;
    height: 318rpx;
    vertical-align: top;
  }
}

.day {
  position: relative;
  margin-bottom: -10rpx;
  img {
    width: 694rpx;
    height: 260rpx;
    vertical-align: top;
  }
  .d-number {
    position: absolute;
    font-size: 36rpx;
    width: 118rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    color: #fff;
    font-weight: bold;
    left: 190rpx;
    bottom: 66rpx;
  }
}
.f-battle{
  margin-bottom: -20rpx;
  img{
    width: 694rpx;
    height: 240rpx;
  }
}
.logo {
  width: 294rpx;
  height: 294rpx;
  margin-bottom: 200rpx;
}
.btn-success {
  margin-bottom: 60rpx;
}


.small-btn{
  display: flex;
  justify-content: center;
  img{
    width: 354rpx;
    height: 228rpx;
  }
  .service {
  width: 354rpx;
  height: 228rpxrpx;
  padding: 0;
  border: none;
  img{
    width: 100%;
    height: 100%;
  }
}
}
.login-page {
  position: fixed;
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background-size:750rpx 714rpx;
  background-position: bottom;
  background-repeat: no-repeat;
  background-image: url('');
  &>img{
    width: 294rpx;
    height: 294rpx;
    margin-bottom: 326rpx;
  }
  .login-btn {
    width: 450rpx;
    height: 138rpx;
    line-height: 138rpx;
    font-size: 48rpx;
    background: #67c29f;
    border-radius: 1000rpx;
    color: #fff;
  }
}
</style>
